package com.zdp.contentcenter.sentinel.test;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sesshomaru
 * @date 2020/9/21 21:26
 *
 * 自定义的sentinel错误页面
 */
@Component
public class MyUrlBlockHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {

        ErrorMsg msg = null;
        if (e instanceof FlowException) {
            // 限流异常
            msg = ErrorMsg.builder()
                    .status(100)
                    .msg("限流了")
                    .build();
        }
        else if (e instanceof DegradeException) {
            // 降级异常
            msg = ErrorMsg.builder()
                    .status(101)
                    .msg("降级了")
                    .build();
        }
        else if (e instanceof ParamFlowException) {
            // 参数热点异常
            msg = ErrorMsg.builder()
                    .status(102)
                    .msg("热点参数限流了")
                    .build();
        }
        else if (e instanceof SystemBlockException) {
            // 系统规则异常
            msg = ErrorMsg.builder()
                    .status(103)
                    .msg("系统规则(负载/.. 不满足要求)")
                    .build();
        }
        else if (e instanceof AuthorityException) {
            // 授权异常
            msg = ErrorMsg.builder()
                    .status(104)
                    .msg("授权规则不通过")
                    .build();
        }
        //设置状态码
        httpServletResponse.setStatus(500);
        //避免中文乱码
        httpServletResponse.setCharacterEncoding("utf-8");
        //表示返回的是json数据
        httpServletResponse.setHeader("Content-Type","application/json;charset=utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        // spring mvc 自带的json工具 jackson
        new ObjectMapper().writeValue(
                httpServletResponse.getWriter(),
                msg
        );

    }
}


@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class ErrorMsg {
    private Integer status;
    private String msg;
}
